﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using VMC.Web.Logic;
using VMC.Domain.Model.Service;
using VMC.Domain.Model.Service.Abstract;
using VMC.Domain.Model.Account;
using System.Web.Security;

namespace VMC.Web.Controllers.User
{
    [Authorize]
    public class AccountController : Controller
    {

        private string ViewBasePath = "~/Views/User/";
        private IAccountModelService iAccount;
        public AccountController() : this(new AccountModelService()) { }
        public AccountController(IAccountModelService AccountService)
        {
            iAccount = AccountService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UpdateProfile()
        {
            return View(ViewBasePath + "UpdateProfile.cshtml", iAccount.GetUserProfile(User.Identity.Name));
        }

        [HttpPost]
        public ActionResult UpdateProfile(UpdateProfile Model)
        {
            if (ModelState.IsValid)
            {
                if (iAccount.UpdateProfile(Model))
                {
                    return View(ViewBasePath + "UpdateProfileSuccess.cshtml");
                }
                else
                {
                    ModelState.MergeServiceErrors(iAccount.GetErrors());
                    ModelState.AddModelError("", "Unable to update your profile.");
                }
            }
            return View(ViewBasePath + "UpdateProfile.cshtml", Model);
        }

        public ActionResult ChangePassword()
        {
            return View(ViewBasePath + "ChangePassword.cshtml");
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePassword Model)
        {
            Model.UserName = User.Identity.Name; //This is very critical line of code. 
            if (Model.NewPassword != Model.ConfirmPassword)
            {
                ModelState.AddModelError("NewPassword", "The new password and confirmation password do not match.");
            }
            if (ModelState.IsValid)
            {
                if (iAccount.ChangePassword( Model))
                    return View(ViewBasePath + "ChangePasswordSuccess.cshtml");
                else
                {
                    ModelState.MergeServiceErrors(iAccount.GetErrors());
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }
            return View(ViewBasePath + "ChangePassword.cshtml", Model);
        }

    }
}
